/**
 * create by young (young2f@outlook.com) on 2020/9/16
 */


'use strict';
import React from 'react';
import {AutoComplete, Button, DatePicker, Form, Input, InputNumber, notification, Select, Table} from 'antd';

import FormBase from '../../../components/Base/FormBase';
import {connect} from "dva";
import moment from 'moment';
import 'moment/locale/zh-cn';
import ViewTitle from "../../../components/ViewTitle";
import {FormField, FormLayout, ModalFooter, SearchForm} from "antd-extra";
import notify from "../../../components/NotificationExtra";
import styles from "../../index.less";
import AutoCompletePlus from "../../../common/AutoCompletePlus";


const {RangePicker} = DatePicker;

const {Option} = Select;
moment.locale('zh-cn');
const table = 'ProcureOrder';
@Form.create()
@connect(({
            user,
            global,
            material,
            store, procure
          }) => ({...user, ...material, ...global, ...procure, ...store}))
export default class XXModalSelectProcureMaterialLot extends FormBase {
  constructor(props) {
    super(props);
    const {record = {}} = this.props;
    const {pmLotId} = record;
    this.state = {...record, selectedRowKeys: [pmLotId]};
  }

  componentDidMount() {
    this.props.dispatch({
      type: 'global/getModel',
      payload: {table}
    });
    const payload = this.props.form.getFieldsValue();
    console.log('payload', payload);
    delete payload.storeCount;
    delete payload.materialContent;
    delete payload.materialCount;
    delete payload.cost;
    this.props.dispatch({
      type: 'procure/findMaterialRecordMany',
      payload
    });
    //this.onDataLoad().then(res => this.setState(res));
    const {selectMaterialCode, selectMaterial} = payload;
    console.log('selectMaterialCode', selectMaterialCode);
  }

  renderFoot = () => {
    const {foot, value, modalRef, form, callback, materialRecords = []} = this.props;
    if (foot) {
      return foot(value, modalRef);
    } else {
      return (
        <ModalFooter>
          <Button type="primary" onClick={() => {
            const {modalRef} = this.props;
            form.validateFields((err, values) => {
              if (err) {
                const {code} = err;
                const {errors} = code;
                errors.forEach(item => {
                  notification.error(item);
                });
                return;
              }

              const {selectedRowKeys} = this.state;
              console.log('selectedRowKeys', selectedRowKeys);
              if (selectedRowKeys.length === 0 || selectedRowKeys[0] === undefined) {
                notify({type: "error", message: "请选择物料"});
                return;
              }
              const pmLotId = selectedRowKeys[0];
              const material = _.find(materialRecords, item => {
                console.log("material record item", item.pmLotId, "selected", pmLotId);
                return item.pmLotId === pmLotId;
              });
              console.log(material);
              const {count} = material;
              const {materialCount} = values;
              if (materialCount > count) {
                notify({type: "error", message: "注意！物料用量大于采购可用数量！"});
                //  return;
              }
              _.merge(values, material);

              callback(values);
              modalRef.close();
            });
          }}>确定</Button>
          <Button onClick={() => {
            modalRef.close();
          }}>取消</Button>
        </ModalFooter>
      );
    }
  };


  getMaterialInfo() {
    const {form, count = 0} = this.props;
    const {
      materialContent = this.state.materialContent,
      price = this.state.price
    } = form.getFieldsValue();
    console.log(this.state);
    const materialCount = count * materialContent / 100;

    const cost = price * materialCount;
    return <div>
      <FormLayout form={form} cols={4}>
        <FormField
          label={'原料含量%'}
          required={true}
          name={'materialContent'} initialValue={materialContent}
        >
          <InputNumber style={{width: '100%'}}></InputNumber>
        </FormField>
        <FormField

          label={'原料用量'} required
          name={'materialCount'} initialValue={materialCount}
        >
          <InputNumber disabled style={{width: '100%'}}></InputNumber>
        </FormField>

        <FormField
          label={'成本'}
          name={'cost'} initialValue={cost}
        >
          <Input disabled style={{width: '100%'}}></Input>
        </FormField>

      </FormLayout>;
    </div>;
  }

  getMaterialOpt = (list) => {

    return list.map(opt => (
      <Option key={opt.code}
              value={opt.name + " " + opt.subcategory + " " + opt.spec + " " + opt.type + " " + opt.number + " " + opt.code}
              label={'material'}>
        {/*{<Tooltip title={opt.code+opt.name+" "+opt.subcategory+" "+opt.spec}> {opt.name}</Tooltip>}*/}
        {opt.name + " " + opt.subcategory + " " + opt.spec + " " + opt.type + " " + opt.number + " " + opt.code}
      </Option>
    ));
  };
  onSearch = searchText => {
    const {materials = []} = this.props;
    console.log('searchText', searchText);
    if (!searchText || searchText === '') {
      this.state.materials = materials;
      const _temp = this.state;
      this.setState(_temp);
      return;
    }
    console.log('searchText materials', this.props.materials);
    const temp = [];
    _.map(this.props.materials, item => {
      const {name} = item;
      if (name.includes(searchText)) {
        temp.push(item);
      }
    });
    const _temp = this.state;
    _temp.materials = temp;
    this.setState(_temp);
  };
  getSearchFields = () => {
    return [
      <FormField
        label="物料名称"
        name="name"
        key={0}
      >
        <Input allowClear placeholder={`请输入物料名称`}/>
      </FormField>,
      <FormField
        label="物料编码"
        name="code"
        key={1}
      >
        <Input allowClear placeholder={`请输入物料编码`}/>
      </FormField>,
      <FormField
        label="形态"
        name="subcategory"
        key={2}
      >
        <Input allowClear placeholder={`请输入物料形态`}/>
      </FormField>,
      <FormField
        label="物料规格"
        name="spec"
        key={3}
      >
        <Input allowClear placeholder={`请输入物料规格`}/>
      </FormField>,
      <FormField
        label="物料编号"
        name="number"
        key={4}
      >
        <Input allowClear placeholder={`请输入物料编号`}/>
      </FormField>,
      <FormField
        label="供应商"
        name="vendor"
        key={5}
      >
        <Input allowClear placeholder="请输入供应商"/>
      </FormField>,

      <FormField
        label="创建时间"
        name="createdTs"
        key={6}
        initialValue={[this.getSearchStart1Months(), this.getDefaultSearchEndDate()]}
      >
        <RangePicker allowClear={true}
          // style={{ width: '150%' }}
        />
      </FormField>

    ];
  };
  cols = [

    {
      title: "物料编码", dataIndex: 'code', key: 'code', render: (value, record) => {
        const {code, name, unit} = record;
        return this.getProductionElement(code, name, unit);
      }
    },
    {title: "采购单编码", dataIndex: 'procureOrderCode', key: 'procureOrderCode'},
    {title: "形态", dataIndex: 'subcategory', key: 'subcategory'},
    {title: "物料规格", dataIndex: 'spec', key: 'spec'},
    {title: "物料编号", dataIndex: 'number', key: 'number'},
    {title: "供应商", dataIndex: 'vendor', key: 'vendor'},
    {title: "去向", dataIndex: 'target', key: 'target'},
    {title: "单价", dataIndex: 'price', key: 'price'},
    {title: "采购数量", dataIndex: 'count', key: 'count'},
    {
      title: "可用数量", dataIndex: 'count', key: 'count', render: (value, record) => {
        const {useCount = 0} = record;
        const color = value - useCount > 0 ? '#22f' : '#f22';
        return <div style={{color}}>{value - useCount}</div>;
      }
    },
    {title: "运费", dataIndex: 'shippingFee', key: 'shippingFee'},
    {title: "入库数量", dataIndex: 'inboundCount', key: 'inboundCount'},
    {
      title: "采购时间", dataIndex: 'createdTs', key: 'createdTs', render: value => {
        return <div>{moment(value).format('YYYY-MM-DD HH:mm:ss')}</div>;
      }
    }

  ];
  onSelectChange = (selectedRowKeys, record) => {
    this.setState({...record, selectedRowKeys});
  };

  render() {
    const {style, materialRecords = [], form} = this.props;
    const {
      selectedRowKeys, loading, pmLotId,
      name,
      subcategory = "", spec = "", type = "",
      number = "",
      materials = [], selectMaterialCode,
    } = this.state;

    if (selectedRowKeys.length > 0 && selectedRowKeys[0] !== undefined) {
      const temp = _.find(materialRecords, item => {
        return item.pmLotId === selectedRowKeys[0];
      });

      if (temp) {
        _.remove(materialRecords, item => {
          return item.pmLotId === selectedRowKeys[0];
        });
        materialRecords.unshift(temp);
      }
    }
    const rowSelection = {
      type: "radio",
      selectedRowKeys,
      onChange: this.onSelectChange
      // getCheckboxProps: record => ({
      //   disabled: _.find(selectedDevices, item => {
      //     console.log(item.code, "disabled", record.code);
      //     return item.code === record.code;
      //   })
      // })
    };
    const onSelectRow = (record) => {
      const {pmLotId} = record;
      const temp = _.find(selectedRowKeys, item => {
        return item === pmLotId;
      });
      if (temp) {
        _.remove(selectedRowKeys, item => item === pmLotId);
      } else {
        selectedRowKeys.length = 0;
        selectedRowKeys.push(record.pmLotId);
      }
      this.onSelectChange(selectedRowKeys, record);
    };
    const str = pmLotId ? `已选择物料：${name} ${subcategory} ${spec} ${type} ${number}` : "";
    const payload = this.props.form.getFieldsValue();
    const {materialContent = 0, } = payload;
    console.log('ssselect material', selectMaterialCode);
    return (
      <Form style={{...style}}>
        {/*{this.getMaterialInfo()}*/}
        {this.getMaterialInfo()}
        {materialContent === 0 && <div style={{marginLeft: '24px', color: '#f22'}}>请输入原料含量</div>}
        {
          // <FormLayout form={form} cols={1}>
          //     <FormField
          //       label={'选择原料'}
          //       name={'material'}
          //       required={true}
          //       initialValue={material}
          //     >

          materialContent > 0 && <AutoCompletePlus style={{width: '60%', marginTop: '12px'}}
                                                   addonBefore="选择物料"

                                                   dataSource={this.getMaterialOpt(materialRecords)}
                                                   allowClear
                                                   onSearch={this.onSearch}
                                                   onChange={value => {
                                                     console.log(value);
                                                     form.setFieldsValue({store: undefined});
                                                   }}
                                                   onSelect={(value, option) => {
                                                     const {key, props} = option;

                                                     this.state[`selectMaterialCode`] = key;
                                                     this.state[`selectMaterial`] = value;

                                                     const material = _.find(materialRecords, item => {
                                                       return item.code === key;
                                                     });
                                                     if (!material) return;
                                                     const {
                                                       subcategory,
                                                       number,
                                                       code,
                                                       name,
                                                       spec,
                                                       type,
                                                       unit
                                                     } = material;
                                                     form.setFieldsValue({
                                                       name,
                                                       code,
                                                       subcategory,
                                                       number,
                                                       spec,
                                                       type,
                                                       unit
                                                     });

                                                     this.componentDidMount();
                                                   }}
          >
          </AutoCompletePlus>
          // </FormField> </FormLayout>
        }
        {/*{materialContent > 0 && <ViewTitle*/}
        {/*  title={'采购原料清单'}*/}
        {/*  subTitle={str}*/}
        {/*></ViewTitle>}*/}
        {/*{*/}
        {/*  materialContent===0&&<div style={{marginLeft:'24px'}}>请输入原料含量</div>*/}
        {/*}*/}
        {/*{materialContent > 0 && <SearchForm*/}
        {/*  style={{marginLeft: '6px', marginRight: '6px'}}*/}
        {/*  onSearch={() => {*/}
        {/*    this.state.current = 1;*/}
        {/*    this.componentDidMount();*/}
        {/*  }}*/}
        {/*  onReset={this.handleReset}*/}
        {/*  cols={3}*/}
        {/*  min={6}*/}
        {/*  expandText="展开"*/}
        {/*  form={form}*/}
        {/*>*/}
        {/*  {this.getSearchFields()}*/}
        {/*</SearchForm>}*/}
        {materialContent > 0 && selectMaterialCode && <Table
          className={styles.antTable}
          bordered={true}

          columns={this.cols}
          dataSource={materialRecords}
          scroll={{x: true}}
          loading={loading}
          rowKey={record => record.pmLotId}
          rowSelection={rowSelection}
          onRow={(record) => ({
            onClick: () => onSelectRow(record)
          })}
          pagination={{
            current: this.state.current,
            total: this.state.total,
            showSizeChanger: true,
            onChange: page => {
              this.state.current = page;
              this.componentDidMount();
            },
            onShowSizeChange: (current, pageSize) => {
              this.state.current = 1;
              this.state.pageSize = pageSize;
              this.componentDidMount();
            }
          }}
        ></Table>}

        {materialContent > 0 && this.renderFoot()}
      </Form>
    );
  }
}

